﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CrankShaftAnalysisSystem.Devices;

namespace CrankShaftAnalysisSystem.Controller
{
    public class SafeController
    {
        public MeasureSystem system;
        public System.Timers.Timer SafeTimer { get; private set; }

        public bool Initialized { get; private set; } = false;
        public static bool ManualStop { get; private set; } = false;
        private double current_height = 0;
        public static void StopAll()
        {
            ManualStop = true;
        }

        public SafeController()
        {
            system = MeasureSystem.Instance;
            SafeTimer = new System.Timers.Timer();
            SafeTimer.Interval = 20;
            SafeTimer.AutoReset = true;
            SafeTimer.Elapsed += SafeTimer_Elapsed;
        }

        private void SafeTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            if(system.Easten.PenCompressionReached())
            {
                if(system.PLC.Device.Axis3.ActualVel < 0)
                {
                    system.PLC.SetSpeed(3, 0);
                    Console.WriteLine(@"[Safe Controller]: Axis3 Can't Move Down.");
                }
            }

            if(system.PLC.PartCanBePlaced)
            {
                if(system.PLC.Device.Axis1.ActualVel != 0)
                {
                    system.PLC.SetSpeed(1, 0);
                    Console.WriteLine(@"[Safe Controller]: Axis1 Can't Move.");
                }
            }

            if(system.PLC.Device.Axis2.ActualVel != 0)
            {
                current_height = LinearLC485.Instance.ReadLinearDis();
                if (LinearLC485.Instance.Warning || current_height < MeasureSystem.MeasureSetting.LowerLimit || current_height > MeasureSystem.MeasureSetting.UpperLimit)
                {
                    ManualStop = true;
                    system.PLC.SetSpeed(2, 0);
                    Console.WriteLine(@"[Safe Controller]: LC485 Data Error.");
                }
            }

            if(ManualStop)
            {
                MeasureSystem.Instance.SafetyFinishMeaure();
            }

            if(Tools.GetBitState(system.PLC.Device.Info.ButtonInfo, VirtualDevice.Mask.RESET))
            {
                ManualStop = false;
            }

            if (Tools.GetBitState(system.PLC.Device.Info.ButtonInfo, VirtualDevice.Mask.STOP))
            {
                ManualStop = true;
            }

            if (!Tools.GetBitState(system.PLC.Device.Info.SafeInfo, VirtualDevice.Mask.EMERGENCY))
            {
                ManualStop = true;
            }
        }

        public void Begin()
        {
            Initialized = true;
            SafeTimer.Start();
        }
    }
}
